﻿using HY.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System;
using WebApi.Helpers;
using WebApi.Model;
using WebApi.ViewModel;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class YRecordController : BaseController
    {
        public YRecordController(ILogger<YRecordController> logger) : base(logger)
        {
        }

        /// <summary>
        /// 获取购买备案信息分页列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("GetPageList")]
        public async Task<ReturnModel> GetPageList(QueryYRecordVM model)
        {
            try
            {
                Expression<Func<YRecord, bool>> filter = e => true;
                if (!string.IsNullOrEmpty(model.GNumber))
                    filter = filter.And(c => c.GNumber.Contains(model.GNumber));
                if (!string.IsNullOrEmpty(model.GCompany))
                    filter = filter.And(c => c.GCompany.Contains(model.GCompany));
                if (model.BeginTime != null)
                    filter = filter.And(c => model.BeginTime <= c.TransTime);
                if (model.EndTime != null)
                    filter = filter.And(c => model.EndTime >= c.TransTime);
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel { PageIndex = model.PageIndex, PageSize = model.PageSize };
                var data = await DbHelper.YRecord.GetPageListAsync(filter, pageModel);
                return new ReturnModel { Count = pageModel.TotalCount, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(YRecordController)}/{nameof(GetPageList)}", ex);
            }
        }

        [HttpPost("Delete/{id}")]
        public async Task<ReturnModel> Delete(int id)
        {
            try
            {
                YRecord model = DbHelper.YRecord.GetById(id);
                await DbHelper.YRecord.DeleteAsync(it => it.Id == id);
                LogToDB("YRecord", "删除", $"参数：{id},删除数据：{JsonConvert.SerializeObject(model)}", "成功");
                return new ReturnModel { Count = 1 };
            }
            catch (Exception ex)
            {
                LogToDB("YRecord", "删除", $"参数：{id}", "异常", $"{nameof(Delete)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(ReportController)}/{nameof(Delete)}", ex);
            }
        }
    }
}
